package com.aaa.controller;

import com.aaa.entity.Product;
import com.aaa.entity.Ptype;
import com.aaa.service.ProductService;
import com.aaa.service.PtypeService;
import com.aaa.util.DefaultMsg;
import com.aaa.util.TableData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Repository
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private PtypeService ptypeService;
    @RequestMapping("/toList")
    public String tolist(){
        return "product/list";
    }
    @RequestMapping("/listData")
    @ResponseBody
    public TableData<Product> listData(@RequestParam(defaultValue = "") String keyword, Integer page, Integer limit){
        TableData<Product> page1 = productService.page(keyword, page, limit);
        return page1;
    }
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public DefaultMsg saveOrUpdate(Product product){
        DefaultMsg defaultMsg = productService.saveOrupdate(product);
        return defaultMsg;

    }

    @RequestMapping("/toEdit")
    public String toEdit(){
        return "product/edit";
    }

    /**
     *  根据商品编号删除商品信息
     * @param pid
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public DefaultMsg delete(Long pid){
        DefaultMsg defaultMsg = productService.delete(pid);
        return  defaultMsg;
    }
    @RequestMapping("/listAllPtypes")
    @ResponseBody
    public List<Ptype> listAllPtypes(){
        List<Ptype> ptypes = ptypeService.listAll();
        return ptypes;
    }
    @RequestMapping("/upload")
    @ResponseBody
    public DefaultMsg upload(MultipartFile file){
        String saveName= UUID.randomUUID().toString();
        File saveFile = new File("D:/upload/" + saveName);
        DefaultMsg defaultMsg = new DefaultMsg();
        try {
            file.transferTo(saveFile);
            defaultMsg.setTarget(saveName);
        } catch (IOException e) {
            defaultMsg.setError("上传文件失败");
            e.printStackTrace();
        }
        return defaultMsg;
    }
}
